
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.ExamRefer;
import com.rt.schedulebase.mapper.ExamReferItemMapper;
import com.rt.schedulebase.mapper.ExamReferMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.PageVO;
import com.rt.schedulenew.utils.util.DateUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ExamReferServiceImpl extends ServiceImpl<ExamReferMapper, ExamRefer> implements IExamReferService {
    @Autowired
    private ExamReferItemMapper referItemMapper;
    @Autowired
    private IExamScheduleItemService examScheduleItemService;
    @Autowired
    private IExamApplyItemService examApplyItemService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private ICommonService commonServiceImpl;

    @Override
    public int insert(ExamRefer entity) {
        return baseMapper.insert(entity);
    }


    /**
     * 获取虚单预约数据
     *
     * @param dto
     * @return
     */
    @Override
    public JsonResult getExamReferSchedules(ExamApplyDto dto) {
        Page<?> page = null;
        if (dto.getPageSize() != null) {
            page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        }
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        dto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
        dto.setItemNames(CommonUtil.split2List(dto.getItemNameStr()));
        String customExcelSortSetStr = configService.getConfigByName(ConstantsUtil.ConfigName.YY_CUSTOMEXCEL_SORT_SET_BY_VIRTUAL_ORDER.getKey());
        if (StringUtils.isNotBlank(customExcelSortSetStr) && (StringUtils.isNotBlank(dto.getSortFieldOrderStr()) && StringUtils.isNotBlank(dto.getDesc()))) {
            ConfigDto.SortSet customExcelSortSet = JsonUtil.toBean(customExcelSortSetStr, ConfigDto.SortSet.class);
            if (customExcelSortSet != null) {
                String sortField1 = customExcelSortSet.getSortField();
                String sortOrder1 = customExcelSortSet.getSortOrder();
                String sortField2 = customExcelSortSet.getSortField2();
                String sortOrder2 = customExcelSortSet.getSortOrder2();
                String sortFieldOrderStr = CommonUtil.convertSql(sortField1, sortOrder1, sortField2, sortOrder2);
                dto.setSortFieldOrderStr(sortFieldOrderStr);
                dto.setDesc("");
            }
        }
        if (StringUtils.isNotBlank(dto.getCommonCard())) {
            dto.setIsRefer("1");
            List<String> sickIds = commonServiceImpl.getSickIds(dto);
            if (sickIds.size() == 0) {
                return JsonResultUtil.failure("没有您的检查申请记录,如有疑问请到护士站咨询");
            }
            dto.setSickIds(sickIds);
        }
        List<ExamApplyDto> list = baseMapper.getExamRefers(dto);
        List<ExamApplyDto> newList = new ArrayList<>();
        for (ExamApplyDto examApply : list) {
            examApply.setScheduleStatus(CommonUtil.turnScheduleStatus(examApply.getScheduleStatus()));
            List<ExamReferItemDto> referItemDtos = referItemMapper.findByApplyNo(examApply.getApplyNo());
            List<String> itemNames = new ArrayList<>();
            List<String> itemCodes = new ArrayList<>();
            List<String> mergeNos = new ArrayList<>();
            List<ExamApplyItemDto> applyItemDtos = new ArrayList<>();
            for (ExamReferItemDto referItemDto : referItemDtos) {
                itemNames.add(referItemDto.getItemName());
                itemCodes.add(referItemDto.getItemCode());
                mergeNos.add(referItemDto.getApplyId() + "-" + referItemDto.getItemNo());
                ExamApplyItemDto applyItemDto = new ExamApplyItemDto();
                applyItemDto.setExamClass(examApply.getExamClass());
                applyItemDto.setItemName(referItemDto.getItemName());
                applyItemDto.setItemCode(referItemDto.getItemCode());
                applyItemDto.setOrgans(referItemDto.getOrgans());
                if (Objects.equals(examApply.getMemo(), "会诊")) {
                    examApply.setIsSign("1");
                }
                applyItemDtos.add(applyItemDto);
            }
            boolean isExamClass4Organ = configService.getOrganExamClassList().contains(examApply.getExamClass());
            double organs = 1.0;
            if (isExamClass4Organ) {
                organs = commonServiceImpl.getReqOrganByItems(applyItemDtos);
            }
            examApply.setMergeNo(StringUtils.join(mergeNos, ";"));
            examApply.setItemNameStr(StringUtils.join(itemNames, ";"));
            examApply.setItemCodeStr(StringUtils.join(itemCodes, ";"));
            examApply.setApplyId(examApply.getApplyNo());
            examApply.setOrgans(organs);
            examApply.setItems(applyItemDtos);
            newList.add(examApply);
        }
//        Set<ExamApplyDto> applyDtos = new HashSet<>(newList);
//        newList.clear();
//        newList.addAll(applyDtos);
        PageVO pageVO = new PageVO();
        if (dto.getPageSize() != null) {
            pageVO.setPageNo(dto.getPageNo());
            pageVO.setPageSize(dto.getPageSize());
            pageVO.setTotal(page.getTotal());
            pageVO.setPages(page.getPages());
        }
        return JsonResultUtil.success("成功", newList, pageVO);
    }

    @Override
    public int update(ExamRefer entity) {
        return baseMapper.update(entity);
    }

    @Override
    public int updateReal(ExamRefer entity, List<ExamApplyItemDto> lsExamSchedule) {
        baseMapper.update(entity);
        for (int i = 0; i < lsExamSchedule.size(); ++i) {
            ExamScheduleItemDto examScheduleItem = new ExamScheduleItemDto();
            examScheduleItem.setOldApplyNo(entity.getApplyId());
            examScheduleItem.setOldItemNo(Integer.valueOf(i + 1));
            examScheduleItem.setApplyNo(lsExamSchedule.get(i).getApplyNo());
            examScheduleItem.setItemNo(lsExamSchedule.get(i).getItemNo());
            examScheduleItemService.updateByApplyNo(examScheduleItem);
        }
        return 1;
    }

    @Override
    public int delete(ExamRefer entity) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("APPLY_ID", entity.getApplyId());
        map.put("REAL_APPLY_NO", entity.getRealApplyNo());
        UpdateWrapper<ExamRefer> del = new UpdateWrapper<>();
        del.allEq(map, false);
        return baseMapper.delete(del);
    }

    @Override
    public JsonResult matchRealExamApply(ExamRefer entity) {
        ExamApplyItemDto examApplyItemDto = new ExamApplyItemDto();
        examApplyItemDto.setApplyNos(CommonUtil.mergeNo2ApplyNos(entity.getRealApplyNo()));
        List<ExamApplyItemDto> lsExamSchedule = (List<ExamApplyItemDto>) examApplyItemService.getList(examApplyItemDto);
        if (lsExamSchedule.size() > 0) {
            for (ExamApplyItemDto applyDto : lsExamSchedule) {
                String scheduleStatus = (applyDto.getExamStatus() != null) ? applyDto.getExamStatus() : applyDto.getScheduleStatus();
                if ("01".equals(scheduleStatus) || "08".equals(scheduleStatus) || "10".equals(scheduleStatus) || "40".equals(scheduleStatus)) {
                    return JsonResultUtil.failure("预约申请单已预约、已报到或已检查，无法进行实单匹配");
                }
            }
        }
        String examReferMemo = "【EXAM_REFER】表申请单号:[" + entity.getApplyId() + "]与【EXAM_APPLY】表申请单号:[" + entity.getRealApplyNo() + "] 于 " + DateUtil.getCurrDateStr() + DateUtil.getCurrentTime() + " 进行了关联匹配。";
        ExamRefer examRefer = new ExamRefer();
        examRefer.setApplyId(entity.getApplyId());
        examRefer.setRealApplyNo(StringUtils.join(examApplyItemDto.getApplyNos(), ","));
        examRefer.setScheduleMemo(examReferMemo);
        updateReal(examRefer, lsExamSchedule);
        return JsonResultUtil.success();
    }

    @Override
    public JsonResult cancelMatchExamApply(ExamRefer entity) {
        QueryWrapper<ExamRefer> qw = new QueryWrapper<>();
        qw.eq("APPLY_ID", entity.getApplyId());
        ExamRefer examRefer = baseMapper.selectOne(qw);
        if (examRefer == null) {
            JsonResultUtil.failure("该记录不存在");
        }
        if (StringUtils.isBlank(examRefer.getRealApplyNo())) {
            JsonResultUtil.failure("该虚单关联的实单申请单号为空，请重新选择");
        }
        List<String> applyNos = CommonUtil.split2List(entity.getRealApplyNo());
        for (String applyNo : applyNos) {
            ExamScheduleItemDto examScheduleItemDto = new ExamScheduleItemDto();
            examScheduleItemDto.setApplyNo(applyNo);
            int count = examScheduleItemService.getCount(examScheduleItemDto);
            if (count == 0) {
                JsonResultUtil.failure("在预约表找不到该真实申请单号的预约记录，请重新选择");
            }
        }
        ExamApplyItemDto examApplyItemDto = new ExamApplyItemDto();
        examApplyItemDto.setApplyNos(applyNos);
        List<ExamApplyItemDto> lsExamSchedule = examApplyItemService.getList(examApplyItemDto);
        if (lsExamSchedule.size() > 0) {
            for (ExamApplyItemDto applyDto : lsExamSchedule) {
                String scheduleStatus = (applyDto.getExamStatus() != null) ? applyDto.getExamStatus() : applyDto.getScheduleStatus();
                if ("10".equals(scheduleStatus) || "40".equals(scheduleStatus)) {
                    return JsonResultUtil.failure("预约申请单已报到或已检查，无法进行取消匹配");
                }
            }
        }
        String cancelMatchMemo = "【EXAM_REFER】表申请单号:[" + entity.getApplyId() + "]与【EXAM_APPLY】表申请单号:[" + entity.getRealApplyNo() + "] 于 " + DateUtil.getCurrDateStr() + DateUtil.getCurrentTime() + " 进行了取消关联匹配。";
        ExamRefer er = new ExamRefer();
        er.setScheduleMemo(cancelMatchMemo);
        er.setRealApplyNo("");
        er.setApplyId(entity.getApplyId());
        update(er);
        for (int i = 0; i < applyNos.size(); ++i) {
            ExamScheduleItemDto examScheduleItem = new ExamScheduleItemDto();
            examScheduleItem.setOldApplyNo(applyNos.get(i));
            examScheduleItem.setApplyNo(entity.getApplyId());
            examScheduleItem.setItemNo((long) (i + 1));
            examScheduleItemService.updateByApplyNo(examScheduleItem);
        }
        return JsonResultUtil.success();
    }
}
